package ichubcontext

import (
	"gitee.com/ichub/webcli/common/base/baseconsts"
	"gitee.com/ichub/webcli/common/base/basedto"
	"gitee.com/ichub/webcli/common/base/baseutils/fileutils"
	"log"
	"os"
	"strings"
)

var CommonContext *ichubCommonContext = newIchubCommonContext()

const (
	INPUT_RULE_PATH = "/data/input/rule/"

	OUTPUT_RULE_PATH = "/data/output/rule/"
)

type ichubCommonContext struct {
	basedto.BaseEntity

	BasePath    string
	OutRulePath string
	InRulePath  string
}

func newIchubCommonContext() *ichubCommonContext {
	var ctxt = &ichubCommonContext{}

	ctxt.BasePath = ctxt.FindRootDir()
	ctxt.InRulePath = ctxt.BasePath + INPUT_RULE_PATH
	ctxt.OutRulePath = ctxt.BasePath + OUTPUT_RULE_PATH

	ctxt.InitProxy(ctxt)
	return ctxt
}

func (this *ichubCommonContext) FindRootDir() string {

	var basepath = os.Getenv(baseconsts.IchubBasePath)

	if len(basepath) > 0 {
		return basepath
	}

	return this.FindWinRootDir()
}

func (this *ichubCommonContext) FindWinRootDir() string {

	if os.Getenv(baseconsts.IchubBasePath) != "" {

		return os.Getenv(baseconsts.IchubBasePath)
	}
	// 获取当前工作目录win
	rootDir, err := os.Getwd()
	if err != nil {
		log.Println("Failed to get current working directory: %s", err)
	}
	var dirs = strings.Split(rootDir, "\\")
	var workRoot string
	if len(dirs) < 3 {
		workRoot = "/" + strings.Trim(dirs[1], " ")
	} else {
		workRoot = "/" + strings.Trim(dirs[1], " ") + "/" + dirs[2]
	}
	exist := fileutils.CheckFileExist(workRoot + "/config/ichubengine.yml")
	//os.Chdir(workRoot)
	if exist {
		os.Setenv(baseconsts.IchubBasePath, workRoot)
	} else {
		workRoot = "/" + strings.Trim(dirs[1], " ")
		exist = fileutils.CheckConfigFileExist(workRoot + "/config/ichubengine.yml")
		os.Setenv(baseconsts.IchubBasePath, workRoot)
	}
	return workRoot
}

func (this *ichubCommonContext) WriteDaoFile(daofile string, content string) error {
	//	fileutil.RemoveFile(this.DaoFilePath + daofile)
	//	err := fileutil.WriteStringToFile(this.DaoFilePath+daofile, content, false)
	//	if err != nil {
	//		logrus.Error(err)
	//	}
	return nil
}
